package StudyCode.summary.mydatetime;

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.Month;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.chrono.MinguoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DecimalStyle;
import java.time.temporal.TemporalAccessor;
import java.util.Locale;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class LocalDateToChronoLocalDate {

	public static void main(String[] args) {
		LocalDate date = LocalDate.of(1996, Month.OCTOBER, 29);
		String str = LocalDateToChronoLocalDate.toString(date, MinguoChronology.INSTANCE);
		System.out.println("LocalDate To ChronoLocalDate: " + str);
		System.out.println("ChronoLocalDate To LocalDate: " + fromString(str, MinguoChronology.INSTANCE));
	}

	private static String toString(LocalDate localDate, Chronology chrono) {
		if (localDate != null) {
			ChronoLocalDate cDate;
			if (chrono == null) {
				chrono = IsoChronology.INSTANCE;
			}
			try {
				cDate = chrono.date(localDate);
			} catch (DateTimeException ex) {
				System.err.println(ex);
				chrono = IsoChronology.INSTANCE;
				cDate = localDate;
			}
			String pattern = "M/d/yyyy GGGGG";
			DateTimeFormatter dateFormatter = DateTimeFormatter
					.ofPattern(pattern);
			return dateFormatter.format(cDate);
		} else {
			return "";
		}
	}

	private static LocalDate fromString(String text, Chronology chrono) {
		if (text != null && !text.isEmpty()) {
			Locale locale = Locale.getDefault(Locale.Category.FORMAT);
			if (chrono == null) {
				chrono = IsoChronology.INSTANCE;
			}
			String pattern = "M/d/yyyy GGGGG";
			DateTimeFormatter df = new DateTimeFormatterBuilder()
					.parseLenient().appendPattern(pattern).toFormatter()
					.withChronology(chrono)
					.withDecimalStyle(DecimalStyle.of(locale));
			TemporalAccessor temporal = df.parse(text);
			ChronoLocalDate cDate = chrono.date(temporal);
			return LocalDate.from(cDate);
		}
		return null;
	}

}
